$.ajaxSetup({
    beforeSend: function (xhr) {},
    // dataFilter: function (data, type) {
    // },
    complete: function (xhr, status) {
        // if (xhr.status == "9981" || xhr.status == "0") {
        if (xhr.status == "9981") {
            mui.toast('当前用户会话过期,将要自动跳转登录页面!', {
                duration: 'long',
                type: 'div'
            })
            setTimeout(function () {
                $(location).attr("href", "../index.html");
            }, 1500)

        } else if (xhr.status == "200") {} else {}
    }
});
// 生产模式 （上线之前需打开此模式，uat环境勿打，相邻//中间代码）
let corpid = "ww4d11a39991ebffdc";
let isc_appid = "e6739c561aa14327b2858724d3ef98d6"; //账户 Isc AppId
let sURLgetWxCode = "https://igw.sgcc.com.cn/connect/oauth2/authorize?"
let appid = "ww4d11a39991ebffdc" //写死
let encodeURIComponentUrl = "zipapp://local.host/index.html"
let sURLgetIscToken = "https://id.sgcc.com.cn:10443/ticket/identity/getAuthTicketByWechatCode"
// var localUrlLink = "http://172.20.10.3:"
var localUrlLink = "http://127.0.0.1:"
let magentid = '1003505'
let urlLinkIp = "igw.ssag.sgcc.com.cn"
let urlServeruser = "user" //用户id  写死 不管
let urlServerappid = "AIzhushoudamoxingban" //应用id  不管 后续提供
let urlLocalip = "10.245.38.143"
let urlLinkPort = "20084"
let urlLocalport = "16000"
//
let titcketId = generateUUID()
let nonceStr = "AMQGnmTMzhJetshY" // 必填，生成签名的随机串
let signature = "fb9f560a9b4824f7db3525926994010de74ea055" // 必填，签名，见附录1
let timestamp = Date.now();
let isFlag = false; //true 开发模式 false 生产 
let isFlagOne = false; //true 脱敏 fasle不托
let userId;
let userName;
let unitId;
var homeKey = "df9033616b66f748fae60ee74de1c2640041493566995d4a2217394231ed7a0f"
let isflageIOX = false
let isClicked = false
//获取浏览器的userAgent,并转化为小写
var ua = navigator.userAgent.toLowerCase();
//判断是否是苹果手机，是则是true
var isIos = ua.indexOf("iphone") != -1 || ua.indexOf("ipad") != -1;
if (isIos) {
    isflageIOX = true;
} else {
    isflageIOX = false;
}

var homeKey = "df9033616b66f748fae60ee74de1c2640041493566995d4a2217394231ed7a0f"
let TimeClose = null

var iscp = {
    port: ''
}
let iscp_port
if (sessionStorage.getItem("iscp_port")) {
    iscp_port = sessionStorage.getItem("iscp_port");
} else {
    iscp_port = ""
}
let toMail = "" //公共邮箱
let urlMyLink = urlLinkIp + ':' + urlLinkPort //链路标识 60.28.54.50:20084
let jsApiList = []; //需要使用的功能接口
let vconsole = new VConsole()
vconsole.showSwitch()
// 隐藏 vConsole 的开关按钮
// $(() => {
//     let vconsoleFlag = sessionStorage.getItem("vconsoleFlag")
//     if (vconsoleFlag != "true") {
//         vconsole.hideSwitch()
//     }
// })
// 分享文字接口
function greneralRequest(url, obj, num,fileName) {
    userId = sessionStorage.getItem("userId");
    orgId = sessionStorage.getItem("unitId")
    var fileNames
    const timestamp = new Date().getTime() + ""
    const AuthenticationSession = sessionStorage.getItem("Authentication");
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }
    let data = {
        userId: userId,
        toFile: num ? num : '',
        orgId: orgId,
        timestamp: timestamp
    }
    data = Object.assign({}, JSON.parse(obj), data)
    data = JSON.stringify(data)
    let sign = sm3(data);
    $.ajax({
        // url: url,
        url: localUrlLink + iscp_port + url,
        type: "post",
        async: false, //是否同步，false表示同步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            Authentication: AuthenticationSession,
            sign: sign,
            userId: userId,
            timestamp: timestamp
        },
        success: (res, txt, xhr) => {
            $("#curtain").css("display", "none");
            console.log(xhr.getResponseHeader("sign"), "xhr.getResponseHeader(sign)")
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")
                if (res.code == 200) {
                    console.log(Authentication, "Authentication")
                    if (Authentication) {
                        sessionStorage.setItem("Authentication", Authentication);
                        if (res.resultValue.code == 0) {
                            fileNames = (fileName ? fileName : res.resultValue.fileName) + '.docx'

                            $("#curtain").css("display", "none");
                            wx.invoke("ext_Intent_SystemShare", {
                                data: {
                                    content: res.resultValue.base64String, //具体内容:不要超过1M
                                    contentType: "Base64ToFile", //根据需求填写:1.Base64ToFile2.FilePath3.ToFile 4.仅分享文字则不填写
                                    fileName:unescape(escape(fileNames)) , //自定义:无特殊原因不填,智能推断的就很好
                                }
                            }, function (res) {
                                console.log("ext_Intent_Dial ", res);
                            })
                        } else {
                            $("#curtain").css("display", "none");
                            // 
                            listIds = res.resultValue.id
                            if (num == 1) {
                                $(location).attr("href", `voiceRecordingList.html?title=${data.title}&id=${listIds}&name=${res.resultValue.name}&size=${res.resultValue.size}`);
                                return
                            }
                            channelId = "net_upload_" + createNonceStr(16) + new Date()
                                .getTime() + "";
                            wx.invoke("multiWindows_subscribe", {
                                channelId: channelId
                            }, function (res) {
                                console.log(res.data.result, "监听的数据")
                                if (res.data.event == "success") {
                                    $("#curtain").css("display", "none");
                                    wx.invoke("ext_Intent_SystemShare", {
                                        data: {
                                            content: decodeURIComponent(res.data.result.replace("file://", "")),
                                            contentType: "FilePath",
                                            fileName: unescape(escape(fileNames)),
                                        }
                                    }, function (res) {
                                        if (isflageIOX) {
                                            wx.invoke("getZipAppDirectory", {
                                                "type": "STORAGE_ROOT_DIR", //APP_ROOT_DIR
                                            }, function (res) {
                                                console.log(res, 999)
                                                wx.invoke("ext_FileManager_Remove", {
                                                        "data": {
                                                            fileList: [res.directory +
                                                                unescape(escape(fileNames)),
                                                            ]
                                                        }
                                                    },
                                                    function (res) {
                                                        console.log("ext_FileManager_Remove",
                                                            res);
                                                    })
                                            })
                                        }
                                    })
                                }
                            })
                            //获取绝对路径
                            wx.invoke("getZipAppDirectory", {
                                "type": "STORAGE_ROOT_DIR", //APP_ROOT_DIR
                            }, function (res) {
                                var path = res.directory ? res.directory : ''
                                // 2.开始下载任务
                                let voiceSign = sm3(timestamp + "&" + listIds);
                                wx.invoke("ext_Net_Download", {
                                    data: {
                                        cmd: "download",
                                        url: localUrlLink + iscp_port + `/tjAiAssistant/voice/downloadAudioFileById?Authentication=${sessionStorage.getItem("Authentication")}&id=${listIds}&sign=${voiceSign}&timestamp=${timestamp}`, //下载url地址
                                        header: {},
                                        id: channelId, //与channelId保持一致
                                        timeout: 10,
                                        fileName: unescape(escape(fileNames)), //保存的文件名
                                        path: path //文件保存路径使用getZipAppDirectory获取
                                    }
                                }, function (res) {
                                    if (res.event === 'start') { //任务开始成
                                        console.log("任务id：", res.id)
                                    }
                                    if (res.event === 'fail') { //任务失败
                                    }
                                })
                            })
                        }
                    }
                } else {
                    mui.toast(res.resultValue, {
                        duration: 'long',
                        type: 'div'
                    })
                }
            } else {
                mui.toast('完整性校验失败', {
                    duration: 'long',
                    type: 'div'
                })
            }
        },
        error: (e) => {
            $("#curtain").css("display", "none");
            mui.toast('请求异常,请稍后再试', {
                duration: 'long',
                type: 'div'
            })
        },
    });
};

function getUserMessage(callback) {
    var Read;
    let userId = sessionStorage.getItem("userId");
    let param = {
        "userId": userId,
        "timestamp": new Date().getTime() + "",
    };
    let AuthenticationSession = sessionStorage.getItem("Authentication");
    data = JSON.stringify(param)
    let sign = sm3(data);
    $.ajax({
        url: localUrlLink + iscp_port + "/tjAiAssistant/userMessage/getUserMessage",
        type: "post",
        // async: false, //是否同步，false表示同步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            Authentication: AuthenticationSession,
            sign: sign
        },
        success: (res, txt, xhr) => {
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")
                if (res.code == 200) {
                    if (Authentication) {
                        sessionStorage.setItem("Authentication", Authentication);
                    }
                    let data = res.resultValue
                    callback(data.sysMsgRead && data.announcementRead);
                }
            }

        },
        error: (e) => {

        },

    });
};

function createNonceStr(len) {
    var e = len ? len : 16;
    var t =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
        a = t.length,
        n = "";
    for (i = 0; i < e; i++)
        n += t.charAt(Math.floor(Math.random() * a));
    return n;
};
//  开发环境不走 安全交互
function createISCPLink(int) {
    $("#showP").html(" 正在建立安全连接...")
    $.getScript("./js/jweixin-1.2.0.js" /*"js/jweixin-1.0.0.js"*/ , function () {
        'use strict';
        wx.ready(function () {});
        jsApiList = [
            "getLocation",
            "ext_ISCP_RhConfig",
            "setFloatWindow",
            "openChatWithMsg",
            "shareAppMessage",
            "getAuthCode",
            "ext_FileBrowser_StartPreView",
            "ext_Net_Upload",
            "getLocalResPath",
            "ext_FileManager_Information",
            'ext_ISCP_Init',
            'ext_ISCP_ConnectService',
            'ext_ISCP_GetLocalPort',
            'ext_ISCP_Close',
            'ext_ISCP_Status',
            'ext_Popover_Open',
            'ext_Popover_Close',
            'ext_AudioRecorder_Start',
            "multiWindows_open",
            "multiWindows_close",
            "multiWindows_startWidget",
            "multiWindows_finishWidget",
            "multiWindows_subscribe",
            "multiWindows_publish",
            'shareWechatMessage',
            'ext_FileBrowser_ChooseDir',
            'onMenuShareTimeline',
            'chooseImage',
            'getLocalImgData',
            'previewImage',
            'uploadImage',
            'downloadImage',
            'ext_FileBrowser_ChooseDir',
            'ext_FileBrowser_AppointDirChooseFile',
            'getZipAppDirectory',
            'previewFile',
            'ext_Net_FragmentUpload',
            'startRecord',
            'stopRecord',
            'onVoiceRecordEnd',
            'playVoice',
            'playVoice',
            'stopVoice',
            'onVoicePlayEnd',
            'startRecordVoiceBuffer',
            'onRecordBufferReceived',
            "ext_Intent_SystemShare",
            'stopRecordVoiceBuffer',
            'uploadVoice',
            "ext_AudioRecorder_Stop",
            'downloadVoice',
            'translateVoice',

            'setClipboardData',
            'getClipboardData',

            'openLocation',
            'startAutoLBS',
            'stopAutoLBS',
            'onLocationChange',

            'onHistoryBack',
            'closeWindow',
            'openUrl',

            'scanQRCode',

            'launch3rdApp',

            'ocr',

            'checkJsApi',
        ];
        wx.config({
            beta: true, // 调用wx.invoke形式的接口值时，该值必须为true。
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            appId: appid, // 必填，政务微信的cropID
            timestamp: '1626832073', // 必填，生成签名的时间戳
            nonceStr: nonceStr, // 必填，生成签名的随机串
            signature: signature, // 必填，签名，见附录1
            jsApiList: jsApiList // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
    });
};

function login() {
    var access_token = "";
    let userId = sessionStorage.getItem("userId");
    let data = {
        "userId": userId,
        "timestamp": new Date().getTime() + "" //时间戳
    }
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }
    data = JSON.stringify(data)
    let sign = sm3(data);
    let AuthenticationSession = sessionStorage.getItem("Authentication");
    $.ajax({
        url: localUrlLink + iscp_port + "/pxapi/oauth/getToken",
        type: "post",
        async: false, //是否同步，false表示同步请求 true表示异步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            sign: sign,
            Authentication: AuthenticationSession,
        },
        success: (res, txt, xhr) => {
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")
                if (res.code == 200) {
                    if (Authentication) {
                        sessionStorage.setItem("Authentication", Authentication);
                        access_token = res.resultValue;
                    }
                } else {
                    $(".curtain").css("display", "none");
                    mui.toast(res.resultValue, {
                        duration: 'long',
                        type: 'div'
                    })
                }
            } else {
                $(".curtain").css("display", "none");
                mui.toast('完整性校验失败', {
                    duration: 'long',
                    type: 'div'
                })
            }
        },
        error: (e) => {
            $(".curtain").css("display", "none");
            mui.toast("请求异常，请稍后再试！", {
                duration: 'long',
                type: 'div'
            })
        },

    });
    return access_token;
};


// 关闭连接
function closeIscp() {
    wx.invoke("ext_ISCP_Close", {
        data: {
            iscpIP: magentid
        }
    }, function (res) {
        if (res.err_msg.substr(res.err_msg.lastIndexOf(":")) === ":ok") {}
    });
}

/*操作日志异步公共接口  
    operatorType 1/用户登陆 、登出 2/OCR识别 
    operatorBasic  1/打印 2/手写 3/身份证 4/增值税 5/火车票    
    operatorContent 1//复制文本 2/发送邮箱 3/识别
*/

function addOperator(type, basic, content, isDel, operatorStatus, through, time, pic, name) {
    userId = sessionStorage.getItem("userId");
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }
    let data = {
        "userId": userId, //用户id
        "operator": "", //操作人  现已废弃
        "operatorIP": "001", //操作ip
        "operatorType": type,
        "operatorBasic": basic,
        "operatorContent": content,
        "isDel": isDel, //0：邮箱及同意书数据 1：操作数据
        "operatorStatus": operatorStatus, //操作是否成功 1成功 0失败
        "through": through, //操作失败的原因
        "duration": time, //语音使用时间 秒
        "timestamp": new Date().getTime() + "", //时间戳
        "identificationMark": pic == "picture" ? 5 : name
    }
    data = JSON.stringify(data)
    let sign = sm3(data);
    let AuthenticationSession = sessionStorage.getItem("Authentication");
    let addOperatorList
    let URLS
    // if (pic == "picture") {
    //     URLS = "/photoTransfer/operator/addOperator"
    // } else {
    //     URLS = "/tjAiAssistant/operator/addOperator"
    // }
    $.ajax({
        url: localUrlLink + iscp_port + "/tjAiAssistant/operator/addOperator",
        type: "post",
        async: true, //是否同步，false表示同步请求 true表示异步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            sign: sign,
            Authentication: AuthenticationSession,
        },
        success: (res, txt, xhr) => {
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")
                if (res.code == 200) {
                    if (Authentication) {
                        sessionStorage.setItem("Authentication", Authentication);
                    }
                }
            } else {
                // mui.toast("sign验证失败", {
                //     duration: 'long',
                //     type: 'div'
                // })
            }
            addOperatorList = res
            return addOperatorList
        },
        error: (e) => {},

    });
    return addOperatorList
};

// 验证邮箱
function validateMail(mail) { //校验邮箱
    var reg = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
    let ismail = reg.test(mail);
    if (!ismail) {
        return false
    } else {
        return true
    }
}
/* 发送邮箱公共接口*/
function mailbox(sceneNo, fileName, fileExt, fileContent, orgId, userId, userName, toMail, saveType,timestamp) {
    userId = sessionStorage.getItem("userId");

    orgId = sessionStorage.getItem("unitId")
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }
    // 注册邮箱发送验证码
    if (sceneNo != 41) {
        toMail = sessionStorage.getItem("toMail")
        // let validateMailFlag = validateMail(toMail)
        // 发送邮箱前判断是否注册过
        if (!toMail && saveType == 0) {
            // if (!validateMailFlag) {
            $(".curtain").css("display", "none")
            mui.toast('请前往“我的”页面设置内网邮箱！', {
                duration: 'long',
                type: 'div'
            })
            return
        }
    }
    let msgString
    let newFileContent
    if (sceneNo == 3 || sceneNo == 8) {
        msgString = fileContent + "," + sm3(fileContent)
        newFileContent = sm2.doEncrypt(msgString, sessionStorage.getItem("bpuk"), 1)
    } else {
        newFileContent = fileContent
    }
    let data = {
        "sceneNo": sceneNo,
        "fileName": fileName, //文本名称
        "fileExt": fileExt, //文本后缀名称
        "fileContent": newFileContent, //识别后内容
        "orgId": orgId, //单位id
        "userId": userId, //用户id
        "saveType": saveType, // 3同步0邮箱
        "userName": "", //用户名称
        "toMail": '',
        "timestamp": timestamp
    };
    let AuthenticationSession = sessionStorage.getItem("Authentication");
    data = JSON.stringify(data)
    let sign = sm3(data);
    let mailboxReturn
    $.ajax({
        url: localUrlLink + iscp_port + "/tjAiAssistant/IdentificationFile/fileDataAdd",
        type: "post",
        async: false, //是否同步，false表示同步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            sign: sign,
            Authentication: AuthenticationSession,
        },
        success: (res, txt, xhr) => {
            mailboxReturn = res.code
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")
                if (res.code == 200) {
                    if (Authentication) {
                        sessionStorage.setItem("Authentication", Authentication);
                        if (sceneNo == 41) {
                            $(".curtain").css("display", "none")
                            mui.toast("验证码已发送至内网邮箱", {
                                duration: "long",
                                type: "div",
                            });
                        } else {
                            $(".curtain").css("display", "none")
                            if(saveType == 3) {
                                showConfirmDialog("同步完成，请及时到内网网站aioa.sgcc.com.cn下载使用"," ")
                              } else {
                                mui.toast("已发送成功", {
                                    duration: "long",
                                    type: "div",
                                });
                            }
                           
                        }
                    }

                } else if (res.code == 500) {
                    $(".curtain").css("display", "none")
                    if(saveType == 3) {
                        syncToast('同步失败', 1500, "error", true)
                      } else {
                        mui.toast(res.resultValue, {
                            duration: 'long',
                            type: 'div'
                        })
                    }
                  
                } else {
                    $(".curtain").css("display", "none")
                    mui.toast('请求异常,请稍后再试', {
                        duration: 'long',
                        type: 'div'
                    })
                }
            } else {
                $(".curtain").css("display", "none")
                mui.toast("已发送成功", {
                    duration: "long",
                    type: "div",
                });
            }
            return mailboxReturn
        },
        error: (e) => {
            //  setTimeout(()=>{
            $(".curtain").css("display", "none")
            mui.toast('请求异常,请稍后再试', {
                duration: 'long',
                type: 'div'
            })
            // },2000)
        },
    });
    return mailboxReturn
};

// 退出断开会话
function IscLogout() {
    clearInterval(TimeClose)
    userId = sessionStorage.getItem("userId");
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }
    let data = {
        "userId": userId, //单位id
        "timestamp": new Date().getTime() + ""
    };
    data = JSON.stringify(data)
    let sign = sm3(data);
    let resResult
    let AuthenticationSession = sessionStorage.getItem("Authentication");
    $.ajax({
        url: localUrlLink + iscp_port + "/tjAiAssistant/isc/logout",
        type: "post",
        async: false, //是否同步，false表示同步请求
        dataType: "json",
        data: data,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            Authentication: AuthenticationSession,
            sign: sign
        },
        success: (res, txt, xhr) => {
            if (sm3(res.resultValueStr) == xhr.getResponseHeader("sign")) {
                let Authentication = xhr.getResponseHeader("Authentication")

                if (res.code == 200) {
                    if (Authentication) {
                        sessionStorage.setItem("Authentication", Authentication);
                    }


                } else if (res.code == 500) {
                    mui.toast(res.resultValue, {
                        duration: 'long',
                        type: 'div'
                    })
                } else {
                    mui.toast("请求异常，请稍后再试！", {
                        duration: 'long',
                        type: 'div'
                    })
                }
                resResult = res
                return resResult
            } else {
                mui.toast('完整性校验失败', {
                    duration: 'long',
                    type: 'div'
                })
            }
        },
        error: (e) => {
            if (e.status == "9981") {
                mui.toast('当前用户会话过期,将要自动跳转登录页面!', {
                    duration: 'long',
                    type: 'div'
                })
                setTimeout(function () {
                    $(location).attr("href", "../index.html");
                }, 1000)
            }
        },
    });
    return resResult
}



// 解密姓名
function sm2UserName() {
    let newUserName
    let userNameString = sm2.doDecrypt(sessionStorage.getItem("userName"), sessionStorage.getItem("fprk"), 1)
    let userNameList = userNameString.split(",");
    if (sm3(userNameList[0]) == userNameList[1]) {
        newUserName = userNameList[0]
        return newUserName
    } else {
        return "***"
    }
}
// 手机号脱敏 11位手机号中间四位脱敏显示，例如：187****1234
function noPassByMobile(str) {
    if (null != str && str != undefined) {
        var pat = /(\d{3})\d*(\d{4})/;
        return str.replace(pat, '$1****$2');
    } else {
        return "";
    }
}

// 姓名脱敏 
/**
 * 姓名脱敏处理，规则：3个字以内脱敏第一个字，4—6个字脱敏前两个字，大于6个字脱敏第3—6个字，示例：张三（三）、张三水（三水）、长孙无忌（**无忌）、罗斯托罗司机格（罗斯XXXX格）
 * 
 * 
 */
function noPassByName(str) {
    if (null != str && str != undefined) {
        if (str.length == 2) {
            return str.substring(0, 1) + '*' //截取name 字符串截取第一个字符，
        } else if (str.length == 3) {
            return str.substring(0, 1) + "*" + str.substring(2, 3) //截取第一个和第三个字符
        } else if (str.length > 3) {
            return str.substring(0, 1) + "*" + '*' + str.substring(3, str.length) //截取第一个和大于第4个字符
        }
    } else {
        return "";
    }
}

// 身份证脱敏
function noPassIdCard(str) {
    if (!!str) {
        return str.replace(/(\w{4})\w*(\w{4})/, '$1********$2');
    } else {
        return ""
    }
}

//  银行卡脱敏
function noPassBankCard(str) {
    if (!!str && str.length > 8) {
        return `${str.substring(0, 4)} ${"*".repeat(str.length - 8).replace(/(.{4})/g, `
        $1 `)}${str.length % 4 ? " " : ""}${str.slice(-4)}`;
    } else {
        return ""
    }
}

function ocrSm2(str) {
    
    return sm2.doDecrypt(str, ocrSm2Str)
}
TimeClose = setInterval(() => {
    pantInit()
}, 300000)
// 心跳接口
function pantInit() {
    const userId = sessionStorage.getItem("userId");
    if (sessionStorage.getItem("iscp_port")) {
        iscp_port = sessionStorage.getItem("iscp_port");
    } else {
        iscp_port = ""
    }
    var timestamp = new Date().getTime() + ""
    var AuthenticationSession = sessionStorage.getItem("Authentication");
    let data = {
        userId: userId,
        timestamp: timestamp
    }
    data = JSON.stringify(data)
    let sign = sm3(data);
    $.ajax({
        url: localUrlLink + iscp_port + "/tjAiAssistant/isc/throb",
        type: "post",
        // async: false, //是否同步，false表示同步请求
        data: data,
        dataType: "json",
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            Authentication: AuthenticationSession,
            sign: sign,
            timestamp: timestamp,
            userId: userId
        },
        success: (res, txt, xhr) => {
            let Authentication = xhr.getResponseHeader("Authentication")
            sessionStorage.setItem("Authentication", Authentication);
        },
        error: (e) => {}
    })
}

function closeApp() {
    if (sessionStorage.getItem("outApp")) {
        if (!isFlag) {
            closeIscp();
        }
        IscLogout()
        wx.closeWindow();
        return
    }
}

function generateUUID() {
    var d = new Date().getTime(); //Timestamp
    var d2 = (performance && performance.now && (performance.now() * 1000)) || 0; //Time in microseconds since page-load or 0 if unsupported
    return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16; //random number between 0 and 16
        if (d > 0) { //Use timestamp until depleted
            r = (d + r) % 16 | 0;
            d = Math.floor(d / 16);
        } else { //Use microseconds since page-load if supported
            r = (d2 + r) % 16 | 0;
            d2 = Math.floor(d2 / 16);
        }
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
}

function checkFileNameForSensitiveWords(fileName) {
    const sensitiveWords = ["法轮功", "中共中央办公厅发电", "中共中央办公厅发电", "中办信息综合室", "中办发电", "中办秘书局", "中办通报", "中央委员会", "中央办公厅", "中标价格", "同业对标", "同修", "标底", "二次系统安全防护", "电价调整", "稽核报告", "预算报告", "普通事项", "内部事项", "内部资料", "重要事项", "决算报告", "秘密", "机密", "绝密", "商密", "普通商密", "商业秘密", "核心商密", "安全保卫", "法律纠纷", '邪党', "中长期发展规划", "财务预算报告", "电价调整方案", "城市电网管线", "年度综合计划", "公司驻外津补贴标准", "年度工资总额预算", "工资总额计划", "清算报告", "经济活动分析报告", "年度投资计划报告", "投资完成情况报告", "安全生产事故调查报告", "招标方案", "签报", "薪酬方案", "职工代表提案", "电网地理接线图", "电网年度运行方式报告"];
    for (let i = 0; i < sensitiveWords.length; i++) {
        if (fileName.includes(sensitiveWords[i])) {
            return true;
        }
    }
    return false;
}
function showConfirmDialog(content, title, btnArray = ["取消"], callback) {
    let isHandled = false;
    mui.confirm(
        content,
        title,
        btnArray,
        (e) => {
            if (isHandled) return;
            isHandled = true;
            if (typeof callback === 'function') {
                callback(e.index);
            }
        }
    );
}
function syncToast(msg, duration, type, root) {
    var activeClass = "my-toast-active";
    var f = document.createElement("div");
    var imgSrc = root ? "./yr/images/"+type+".png" : "../../yr/images/"+type+".png"
    return f.classList.add("my-toast-container"), f.innerHTML = '<div class="my-toast-message"><img src="'+imgSrc+'">' + msg + "</div>", f.addEventListener("webkitTransitionEnd", function () {
        f.classList.contains(activeClass) || (f.parentNode.removeChild(f), f = null)
    }), f.addEventListener("click", function () {
        f.parentNode.removeChild(f), f = null
    }), document.body.appendChild(f), f.offsetHeight, f.classList.add(activeClass), setTimeout(function () {
        // f && f.classList.remove(activeClass)
        f.parentNode.removeChild(f), f = null
    }, duration), {
        isVisible: function () {
            return !!f
        }
    }
  }
  /**
 * 获取用户资源权限
 */
function travelAssistance(resId, domId) {
    let resources = JSON.parse(sessionStorage.getItem("newMenus"));
    // resources = [{
    //   'id': 1,
    //   'buttonIds': null
    // },{
    //   'id': 12,
    //   'buttonIds': ['12-trip']
    // }]
    if(null != resources && 0 < resources.length) {
       return resources.some(resource => resId == resource.id && resource.buttonIds && 
        resource.buttonIds.indexOf(domId) != -1)
    }
    return false
  }